/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uc.cech.jonesbr.recursion;

import javax.swing.JOptionPane;

/**
 * Test a palindrome
 * 
 * @author jonesbr
 */
public class Palindrome {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        promptUser();
    }
    
    /**
     * Prompt the user for a phrase.  Figure out if it is a palindrome.
     */
    public static void promptUser() {
        
        // String phrase = JOptionPane.showInputDialog("Enter a phrase.");
        // String phrase = "Go hang a salami, I'm a lasagna hog";
        String phrase = "o";
        String scrubbedPhrase = removeSpecialCharacters(phrase);
        boolean palindrome = isPalindrome(scrubbedPhrase);
        System.out.println("Palindrome? " + palindrome);
    }

    private static String removeSpecialCharacters(String phrase) {
        phrase = phrase.replaceAll("'", "");
        phrase = phrase.replaceAll(" ", "");
        phrase = phrase.replaceAll(",", "");
        phrase = phrase.toLowerCase();
        System.out.println("phrase: " + phrase);
        // System.out.println("Phrase 2: " + phrase1);
        return phrase;
    }
    
    private static boolean isPalindrome(String phrase) {
        boolean isPal = false;
        
        // base case: do we have 1 letter or less?
        if (phrase.length() < 2) {
            // we definitely have a palindrome.
            return true;
        }
        
        // find the first and last letter.  See if they match.
        char firstLetter = phrase.charAt(0);
        char lastLetter = phrase.charAt(phrase.length() - 1);
        
        if (firstLetter == lastLetter) {
            // we may have a palindrome. Recurse
            //first, trim the phrase to a smaller set by removing the characters that we just compared.
            String newPhrase = phrase.substring(1, phrase.length() -1);
            // recurse
            isPal = isPalindrome(newPhrase);
        } else {
            // they are not equal.  WE definitely do not have a palindrome.
            isPal = false;
        }
        
        return isPal;
    }
}
